package com.fcscs.cservice.ws.endpoint;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.fcscs.cservice.common.CServiceCommonEnums;
import com.fcscs.cservice.communication.CommIntfAdaptor;
import com.fcscs.cservice.communication.OutboundHandler;
import com.fcscs.ws.endpoint.EndpointConstants;
import com.fcscs.ws.schemas.communicationservice.SendDataRequest;
import com.fcscs.ws.schemas.communicationservice.SendDataResponse;

@Endpoint("commServiceEndpoint")
public class CommunicationServiceEndpoint {

	@Autowired
	OutboundHandler outHdl;

	@PayloadRoot(localPart = EndpointConstants.SEND_DATA_REQ, namespace = EndpointConstants.COMMUNICATION_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public SendDataResponse sendData(@RequestPayload SendDataRequest req) {
		SendDataResponse resp = new SendDataResponse();
		CServiceCommonEnums.CommAdaptorEnum adp = CServiceCommonEnums.CommAdaptorEnum.valueOf(req.getCommType());
		Map<CommIntfAdaptor.CommParam, Serializable> map = new HashMap<CommIntfAdaptor.CommParam, Serializable>();
		try {
			for (SendDataRequest.Parameter p : req.getParams()) {
				CommIntfAdaptor.CommParam param = CommIntfAdaptor.CommParam.valueOf(p.getName());
				@SuppressWarnings("unchecked")
				Constructor<Serializable> cons = (Constructor<Serializable>)param.getParamClass().getConstructor(String.class);
				map.put(param, cons.newInstance(p.getValue()));
			}
			byte[] res = outHdl.sendBytes("localhost", adp, (String)map.get(CommIntfAdaptor.CommParam.DEVICE), Base64.decodeBase64(req.getData().getBytes()), map);
			resp.setSuccess(res != null);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setSuccess(false);
		}
		return resp;
	}
}
